<?php
namespace app\api\controller;

use app\common\model\MemberModel;
use app\sms\controller\SendSms;
use think\Request;
use think\facade\Cache;

class AccountController extends BaseController{

    /**
     * @param Request $request
     * @return \think\response\Json
     */
    public function index(Request $request){
        $user = $request->user;
        if(empty($user)){
            return backError('用户未登陆');
        }
        return backSuccess($user,'ok');
    }

    /**
     * 发送短信
     * @param Request $request
     * @param string mobile 手机号码
     * @param bool code_status 是否为登陆验证
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendVerify(Request $request){
        //发送验证码
        $mobile = $request->mobile;
        $code_status = $request->code_status;
        if (strlen((int) $mobile) !==11 && !preg_match('/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|16[0-9]{9}$|18[0-9]{9}$|17[0-9]{9}|19[0-9]{9}$/', $mobile)) {
            return backError('手机号码不正确');
        }
        if(empty($code_status)){
            if (MemberModel::where(['mobile'=>$mobile])->find()){
                return backError('该手机号码已注册');
            }
        }

        if($code_status==2){
            if (!MemberModel::where(['mobile'=>$mobile])->find()){
                return backError('用户名错误！');
            }
        }

        $codeTime = Cache::get("codeTime_".$mobile);
        if(!empty($codeTime) && time()-$codeTime <= 60 ){
            return backError('请勿频繁发送验证码');
        }
        $stringNum = "0123456789";
        $code = "";
        for($i=1;$i<=6;$i++){
            $code .= $stringNum{mt_rand(0, 9)};
        }

        Cache::set("codeTime_".$mobile,time(),60); //定义新用户验证码缓存
        Cache::set("newUser_".$mobile,$code,600); //定义新用户验证码缓存

        if(empty($code_status)){
            $status=SendSms::send($mobile,$code);
        }else if($code_status==1){
            $status=SendSms::send($mobile,$code,2);
        }else if($code_status==2){
            $status=SendSms::send($mobile,$code,1);
        }

        if(!$status){
            return backError('发送验证码失败,请联系客服');
        }else{
            return backSuccess(1,'发送验证码成功');
        }
    }

    /**
     * 注册用户
     * @param Request $request
     * @param int mobile 手机号码
     * @param string password 密码
     * @param string code 验证码
     * @return \think\response\Json
     */
    public function register(Request $request) {
        $code = $request->code;
        $password = $request->password;
        $mobile = $request->mobile;

        if(empty(Cache::get("newUser_".$mobile))){
            return backError('短信验证码错误');
        }

        //短信验证逻辑
        $cache_code = Cache::get("newUser_".$mobile);
        if($code == $cache_code && !empty($code) && !empty($cache_code)){
            //新增用户
            $data["mobile"] = $mobile;
            $data["password"] = $password;
            $data["mobile_validated"] = 1;
            $data["oauth"] = $request->from;
            $member = new MemberModel();
            $member->addUser($data);
            Cache::rm("newUser_".$mobile);
            return backSuccess(1,'ok');
        }
        return backError('短信验证码错误');
    }

    /**
     * 找回密码
     * @param Request $request
     * @param int mobile 手机号码
     * @param string password 密码
     * @param string code 验证码
     * @return \think\response\Json
     */
    public function forgetPwd(Request $request) {
        $code = $request->code;
        $password = $request->password;
        $mobile = $request->mobile;

        if(empty(Cache::get("newUser_".$mobile))){
            return backError('短信验证码错误');
        }

        if (!MemberModel::where(['mobile'=>$mobile])->find()){
            return backError('用户名错误！');
        }

        //短信验证逻辑
        $cache_code = Cache::get("newUser_".$mobile);
        if($code == $cache_code && !empty($code) && !empty($cache_code)){

            $data["mobile"] = $mobile;
            $data["password"] = $password;
            $member = new MemberModel();
            $status=$member->updatePwd($data);
            if($status["status"]){
                Cache::rm("newUser_".$mobile);
                return backSuccess(1,'ok');
            }else{
                return backError('修改失败，请稍后再试！');
            }

        }
        return backError('短信验证码错误');
    }

    /**
     * 用户登陆
     *
     * @param Request $request
     * @param int mobile 手机号
     * @param string password 密码
     * @param string code 验证码
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(Request $request){
        $mobile = $request->mobile;
        $password = $request->password;
        $code = $request->code;

        if(!empty($code)){
            //短信登陆
            $cache_code = Cache::get("newUser_".$mobile);
            if($code != $cache_code && empty($cache_code)){
                return backError("短信验证码错误");
            }

            $member = MemberModel::where("mobile",$mobile)->find();

            if(empty($member)){
                //新增用户
                $data["mobile"] = $mobile;
                //$data["password"] = $password;
                $data["mobile_validated"] = 1;
                $data["oauth"] = $request->from;
                $m = new MemberModel();
                $m->addUser($data);
            }

            $member = MemberModel::where("mobile",$mobile)->find();


        }else{
            $member = MemberModel::where("mobile",$mobile)->find();

            if(empty($member)){
                return backError("用户不存在");
            }

            //密码登陆
            if(password($password,$member['salt'])!= $member['password']){
                return backError("密码错误");
            }
        }
        //登陆记录
        $member->last_ip=$request->ip();
        $member->last_login=time();
        $member->save();
        $token=generate_user_token($member->uid,$request->from);
        return backSuccess(["token"=>$token,"user"=>$member]);
    }

    public function update(Request $request){
        $data = $request->data;
        $user = $request->user;

        if(isset($data["pwd"]) && isset($data["pwd1"]) && isset($data["uppwd"])){

            unset($data["uppwd"]);

            if($data["pwd"]!=$data["pwd1"]){
                return backError('密码不一致，请重新输入！');
            }

            $data["password"]=password($data["pwd1"],$user["salt"]);
        }else{
            if(isset($data["uppwd"])){
                return backError('参数错误！');
            }

        }

        $member = MemberModel::find($user["uid"]);
        $res = $member->save($data,['uid'=>$user["uid"]]);
        if($res){
            return backSuccess($member,"修改成功");
        } else {
            return backError("修改失败");
        };

    }
}
